package com.futao.support;

import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author futao
 * Created on 18-6-11-下午2:01.
 */
@Component
@ServletComponentScan
@WebFilter(urlPatterns = "/*", filterName = "myFilter")
public class MyFilter implements Filter {
    private FilterConfig config = null;

    //设置默认的字符编码
    private String defaultCharset = "UTF-8";

    /**
     * web容器启动时会调用init()方法初始化filter
     * filter对象只会创建一次，init方法也只会执行一次
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.config = filterConfig;
        System.out.println("----MyFilter过滤器初始化----");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws
            IOException, ServletException {
        System.out.println("MyFilter过滤器执行前！！！");

        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        /*统一编码*/
        httpServletRequest.setCharacterEncoding(defaultCharset);
        httpServletResponse.setCharacterEncoding(defaultCharset);
        httpServletResponse.setContentType("text/html;charset=" + defaultCharset);

        /*跨域*/
        List<String> allowedOrigins = new ArrayList<>();
        allowedOrigins.add("http://localhost:8080");
        allowedOrigins.add("http://localhost:8888");

        String origin = httpServletRequest.getHeader("Origin");
        System.out.println(".......-------------" + origin);
        String allowedOrigin = "";
        if (allowedOrigins.contains(origin)) {
            allowedOrigin = origin;
        }
        httpServletResponse.setHeader("Access-Control-Allow-Origin", allowedOrigin);
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "PUT, POST, GET, OPTIONS, DELETE");


        /*禁用缓存*/
        httpServletResponse.setDateHeader("Expires", -1);
        httpServletResponse.setHeader("Cache-Control", "no-cache");
        httpServletResponse.setHeader("Pragma", "no-cache");


        chain.doFilter(httpServletRequest, httpServletResponse);  //让目标资源执行，放行

        System.out.println("MyFilter过滤器执行后！！！");
    }

    @Override
    public void destroy() {
        System.out.println("----MyFilter过滤器销毁----");
    }
}
